package com.emo.cloudEdge.service;

import com.emo.cloudEdge.mapper.SuppliersMapper;
import com.emo.cloudEdge.mapper.UserMapper;
import com.emo.cloudEdge.pojo.Return;
import com.emo.cloudEdge.pojo.Suppliers;
import com.emo.cloudEdge.pojo.User;
import com.emo.cloudEdge.util.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * 用户-供应商业务
 */
@Component
public class UserAndSippliersService {
    @Autowired
    private Gson gson;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SuppliersMapper suppliersMapper;

    /**
     * 供应商注册
     * 插入用户和供应商信息
     * @param jsonStr
     * @return
     */
    @Transactional   //事物注解
    public String insertAll(String jsonStr){
        Return res=new Return();
        try{
            gson.setJsonStr(jsonStr);       //设置json数据字符串
            User user=(User) gson.readValueObject(User.class);
            user.setRole(1);        //固定权限
            Suppliers suppliers=(Suppliers) gson.readValueObject(Suppliers.class);
            if(userMapper.selectByAccount(user.getAccount())!=null){
                //已经存在用户名
                res.setMessage("该用户名已存在");
                res.setCode(304);
            }else {
                userMapper.insertAll(user);     //插入User数据
                int user_id=userMapper.selectByAccount(user.getAccount()).getUser_id();     //获取刚刚插入用户的user_id
                suppliers.setUser_id(user_id);      //设置到供应商信息表
                suppliersMapper.insertAll(suppliers);   //插入供应商信息表
                res.setMessage("注册成功");
                res.setCode(200);
            }
        }catch (Exception e){
            res.setMessage("注册失败");
            res.setCode(500);
            e.printStackTrace();
        }
        return gson.toJson(res);
    }
}
